package com.controller;

import com.auth.FrontUserIsLoginAuth;
import com.model.FrontUser;
import com.model.form.FrontUserForm;
import com.model.response.Response;
import com.service.FrontUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/frontUser")
@Api(value = "前端用户接口", tags = "前端用户接口")
public class FrontUserController extends BaseController {

    @Autowired
    private FrontUserService userService;

    @FrontUserIsLoginAuth
    @PostMapping("/getUserInfo")
    public Response getUserInfo() {
        return Response.success(getFrontUserVo());
    }

    @FrontUserIsLoginAuth
    @PostMapping("/hasUser")
    public Response hasUser(String username) {
        if(Strings.isEmpty(username)) return Response.fail("参数错误!");
        boolean result = userService.hasUser(username);
        return Response.success(result);
    }

    @PostMapping("/login")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", defaultValue = "luoyuyi"),
            @ApiImplicitParam(name = "password", defaultValue = "angel009")
    })
    public Response login(@Valid FrontUserForm form) {
        boolean hasFlag = userService.hasUser(form.getUsername(), form.getPassword());
        if(!hasFlag) return Response.fail("用户名或密码错误");
        FrontUser user = userService.updateLoginTime(form.getUsername(), LocalDateTime.now());
        setFrontUser(user);
        return Response.success();
    }

    @PostMapping("/register")
    public Response register(@Valid FrontUserForm form) {
        boolean hasFlag = userService.hasUser(form.getUsername());
        if(hasFlag) return Response.fail("用户名已存在");
        userService.save(form);
        return Response.success();
    }

    @FrontUserIsLoginAuth
    @PostMapping("leave")
    public Response leave(@ApiIgnore HttpSession session) {
        removeFrontUser();
        return Response.success();
    }
}
